﻿using Common;
using IBLL;
using IDAL;
using Models;
using Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    /// <summary>
    /// 用户表的业务逻辑层
    /// </summary>
    public class UserInfoBLL : IUserInfoBLL
    {
        #region 构造函数初始化
        private IUserInfoDAL _userInfoDAL;
        private IUserBalanceInfoDAL _userBalanceInfoDAL;
        private UnmanContexts _dbContext;
        public UserInfoBLL(
            IUserInfoDAL userInfoDAL
            , IUserBalanceInfoDAL userBalanceInfoDAL
            , UnmanContexts dbContext
            )
        {
            _userInfoDAL = userInfoDAL;
            _dbContext = dbContext;
            _userBalanceInfoDAL = userBalanceInfoDAL;
        }
        #endregion

        #region 登录方法（Login）
        /// <summary>
        /// 用户登录业务逻辑
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <param name="msg">返回消息</param>
        /// <param name="userName">返回的用户名</param>
        /// <param name="userId">返回的用户Id</param>
        /// <returns></returns>
        public bool Login(string account, string password, out string msg, out string userName, out string userId)
        {
            //把密码加密为MD5
            string newPassword = MD5Helper.GenerateMD5(password);
            //根据账号密码查询用户
            UserInfo userInfo = _userInfoDAL.GetUserInfos().FirstOrDefault(u => u.Account == account && u.PassWord == newPassword);

            userName = "";
            userId = "";
            //判断是否存在该用户
            if (userInfo == null)
            {
                msg = "账号或密码错误！";
                return false;

            }
            else
            {
                msg = "成功";
                userName = userInfo.UserName;
                userId = userInfo.Id;
                return true;
            }
        }
        #endregion

        #region 查询用户列表的方法(GetUserInfos)
        /// <summary>
        /// 查询用户列表的方法--分页
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="limit">每页几条数据</param>
        /// <param name="account">用户账号</param>
        /// <param name="userName">用户姓名</param>
        /// <param name="count">数据总量</param>
        /// <returns></returns>
        public List<GetUserInfosDTO> GetUserInfos(int page, int limit, string account, string userName, out int count)
        {
            //使用lambda表达式
            //var data = _userInfoDAL.GetEntities().Where(u => u.IsDalete == false).Select(u => new GetUserInfosDTO
            //{
            //    Id = u.Id,
            //    Account = u.Account,
            //    UserName = u.UserName,
            //    Email = u.Email,
            //    PhoneNum = u.PhoneNum,
            //    Sex = u.Sex == 0 ? "女" : "男",
            //    CreateTime = u.CreateTime
            //});
            var data = from u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       join b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false)
                       on u.Id equals b.UserId
                       into tempUB
                       from ub in tempUB.DefaultIfEmpty()
                       select new GetUserInfosDTO
                       {
                           Id = u.Id,
                           Account = u.Account,
                           UserName = u.UserName,
                           PhoneNum = u.PhoneNum,
                           Email = u.Email,
                           CreateTime = u.CreateTime,
                           Sex = u.Sex == 0 ? "女" : "男",
                           Userbalance = ub.Userbalance
                       };
            //用户姓名不能为空
            if (!string.IsNullOrWhiteSpace(userName))
            {
                data = data.Where(u => u.UserName.Contains(userName));
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(u => u.Account == account);
            }
            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(u => u.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;
        }
        #endregion

        #region 添加用户的方法（CreateUserInfo）
        /// <summary>
        /// 添加用户的方法
        /// </summary>
        /// <param name="entity">新用户的实体</param>
        /// <returns></returns>
        public bool CreateUserInfo(UserInfo entity, out string msg)
        {
            //先判断这个用户非空信息
            if (string.IsNullOrWhiteSpace(entity.UserName))
            {
                msg = "用户姓名不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PassWord))
            {
                msg = "密码不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.Account))
            {
                msg = "用户账号不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(entity.PhoneNum))
            {
                msg = "手机不能为空！";
                return false;
            }
            //判断账号是否重复
            UserInfo user = _userInfoDAL.GetEntities().FirstOrDefault(u => u.Account == entity.Account);
            if (user != null)
            {
                msg = "用户账号已经存在";
                return false;
            }
            //赋值id
            entity.Id = Guid.NewGuid().ToString();
            entity.CreateTime = DateTime.Now;
            //加密密码
            entity.PassWord = MD5Helper.GenerateMD5(entity.PassWord);

            //更新到数据库
            bool isSuccess = _userInfoDAL.CreateEntity(entity);
            msg = isSuccess ? $"恭喜{entity.UserName}注册成功！" : "注册失败";
            return isSuccess;

        }



        #endregion

        #region 用户软删除方法（DeleteUserInfo）
        /// <summary>
        /// 用户软删除方法
        /// </summary>
        /// <param name="id">要删除的用户id</param>
        /// <returns></returns>
        public bool DeleteUserInfo(string id)
        {
            //根据id查用户是否存在
            UserInfo userInfo = _userInfoDAL.GetEntityById(id);
            if (userInfo == null)
            {
                return false;
            }
            //修改用户的状态
            userInfo.IsDalete = true;
            userInfo.DeleteTime = DateTime.Now;// 删除时间
            //返回结果
            return _userInfoDAL.UpdateEntity(userInfo);

        }

        #endregion

        #region 批量用户软删除方法(DeleteUserInfo)
        /// <summary>
        /// 批量用户软删除方法
        /// </summary>
        /// <param name="ids">被删除的用户Id集合</param>
        /// <returns></returns>
        public bool DeleteUserInfo(List<string> ids)
        {
            //2/var userList = _userInfoDAL.GetUserInfos().Where(u => ids.Contains(u.I)).ToList();
            foreach (var id in ids)
            {
                //2/ UserInfo userInfo = userList.FirstOrDefault(u => u.Id == id);
                UserInfo userInfo = _userInfoDAL.GetEntityById(id);
                if (userInfo == null)
                {
                    continue;//跳出本次循环
                }
                userInfo.IsDalete = true;
                userInfo.DeleteTime = DateTime.Now;
                //执行修改
                _userInfoDAL.UpdateEntity(userInfo);
            }
            return true;
        }



        #endregion

        #region 更新用户信息方法（UpdateUserInfo）

        /// <summary>
        /// 更新用户信息方法
        /// </summary>
        /// <param name="userInfo">要更新的实体</param>
        /// <param name="msg">返回的描述信息</param>
        /// <returns></returns>
        public bool UpdateUserInfo(UserInfo userInfo, out string msg)
        {
            #region 非空判断
            //非空判断
            if (string.IsNullOrWhiteSpace(userInfo.Id))
            {
                msg = "id不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(userInfo.UserName))
            {
                msg = "用户姓名不能为空！";
                return false;
            }
            //if (string.IsNullOrWhiteSpace(userInfo.PassWord))
            //{
            //    msg = "密码不能为空！";
            //    return false;
            //}
            if (string.IsNullOrWhiteSpace(userInfo.Account))
            {
                msg = "用户账号不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(userInfo.PhoneNum))
            {
                msg = "手机不能为空！";
                return false;
            }
            #endregion

            //判断这个Id是否存在用户
            UserInfo entity = _userInfoDAL.GetEntityById(userInfo.Id);
            if (entity == null)
            {
                msg = "用户id无效";
                return false;
            }
            //先判断是不是跟原来的账号一样，一样表示没有修改
            if (entity.Account != userInfo.Account)
            {
                //通过账号查询数据库里是否存在相同的账号
                UserInfo oldUser = _userInfoDAL.GetEntities().FirstOrDefault(u => u.Account == userInfo.Account);
                if (oldUser != null)
                {
                    msg = "账号已被使用";
                    return false;
                }
            }
            //赋值
            entity.Account = userInfo.Account;
            entity.UserName = userInfo.UserName;
            entity.PhoneNum = userInfo.PhoneNum;
            entity.Email = userInfo.Email;
            entity.Sex = userInfo.Sex;
            //用户的密码，如果传过来的是null或""字符串就使用原来的密码，否则就拿新密码MD5加密使用新密码
            entity.PassWord = string.IsNullOrWhiteSpace(userInfo.PassWord) ? entity.PassWord : MD5Helper.GenerateMD5(userInfo.PassWord);
            //更新到库
            bool isOk = _userInfoDAL.UpdateEntity(entity);
            msg = isOk ? "修改用户成功" : "修改用户失败";
            //返回结果
            return isOk;

        }


        #endregion

        #region 根据用户id获取用户信息的方法(GetUserInfoById)

        /// <summary>
        /// 根据用户id获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public GetUserInfosDTO GetUserInfoById(string id)
        {
            UserInfo user = _userInfoDAL.GetEntityById(id);
            if (user == null)
            {
                return new GetUserInfosDTO();
            }
            //构建返回数据对象
            GetUserInfosDTO userInfo = new GetUserInfosDTO()
            {
                Id = user.Id,
                Account = user.Account,
                UserName = user.UserName,
                Email = user.Email,
                PhoneNum = user.PhoneNum,
                Sex = user.Sex == 1 ? "男" : "女"
            };
            return userInfo;//返回用户信息
        }

        #endregion

        #region 更新用户信息方法(UpdateUserPwd)

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="oldPwd">旧密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="againPwd">确认密码</param>
        /// <param name="msg">返回的消息</param>
        /// <returns></returns>
        public bool UpdateUserPwd(string id, string oldPwd, string newPwd, string againPwd, out string msg)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                msg = "用户的id不能为空!";
                return false;
            }
            if (string.IsNullOrWhiteSpace(oldPwd))
            {
                msg = "原密码不能为空!";
                return false;
            }
            if (string.IsNullOrWhiteSpace(newPwd))
            {
                msg = "新密码不能为空!";
                return false;
            }
            if (newPwd != againPwd)
            {
                msg = "确认密码与新密码不一致!";
                return false;
            }
            //查找用户
            UserInfo userInfo = _userInfoDAL.GetEntityById(id);
            if (userInfo == null)
            {
                msg = "用户不存在!";
                return false;
            }
            //加密
            oldPwd = MD5Helper.GenerateMD5(oldPwd);
            if (userInfo.PassWord != oldPwd)
            {
                msg = "您输入的原密码有误!";
                return false;
            }
            userInfo.PassWord = MD5Helper.GenerateMD5(newPwd);//赋值加密后的新密码给用户
            bool isOk = _userInfoDAL.UpdateEntity(userInfo);//更新用户信息
            msg = isOk ? "修改密码成功!" : "修改密码失败!";
            return isOk;
        }

        #endregion

        #region 查询用户列表的方法(GetUserInfos)
        /// <summary>
        /// 查询用户列表的方法
        /// </summary>

        public List<GetUserInfosDTO> GetUserInfos()
        {
            List<GetUserInfosDTO> userList = _userInfoDAL.GetEntities()
                                                         .Where(x => x.IsDalete == false)
                                                         .Select(x => new GetUserInfosDTO
                                                         {
                                                             Id = x.Id,
                                                             UserName = x.UserName,
                                                             Account = x.Account,
                                                             CreateTime = x.CreateTime,
                                                             Email = x.Email,
                                                             PhoneNum = x.PhoneNum,
                                                             Sex = x.Sex == 0 ? "女" : "男",
                                                         })
                                                         .ToList();
            return userList;
        }
        #endregion
                              
        #region 查询用户列表的方法(GetUsers)
        /// <summary>
        /// 查询用户列表的方法
        /// </summary>

        public List<GetUserInfosDTO> GetUsers(string account, string userName, out int count)
        {
            var data = from u in _dbContext.UserInfo.Where(u => u.IsDalete == false)
                       join b in _dbContext.UserBalanceInfo.Where(b => b.IsDalete == false)
                       on u.Id equals b.UserId
                       into tempUB
                       from ub in tempUB.DefaultIfEmpty()
                       select new GetUserInfosDTO
                       {
                           Id = u.Id,
                           Account = u.Account,
                           UserName = u.UserName,
                           PhoneNum = u.PhoneNum,
                           Email = u.Email,
                           CreateTime = u.CreateTime,
                           Sex = u.Sex == 0 ? "女" : "男",
                           Userbalance = ub.Userbalance
                       };
            //用户姓名不能为空
            if (!string.IsNullOrWhiteSpace(userName))
            {
                data = data.Where(u => u.UserName.Contains(userName));
            }
            //用户账号不能为空
            if (!string.IsNullOrWhiteSpace(account))
            {
                data = data.Where(u => u.Account == account);
            }
            count = data.Count();
            var userList = data.OrderByDescending(m => m.CreateTime).ToList();
            return userList;
        }
        #endregion

    }
}
